package com.hkts.beltweigher.master.controller;


import com.alibaba.fastjson.JSON;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.DoubleStream;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hkts.beltweigher.master.entity.Displaydata;
import com.hkts.beltweigher.master.entity.RandomNumberSettings;
import com.hkts.beltweigher.master.entity.YbClassesAccumulate;
import com.hkts.beltweigher.master.mapper.YbClassesAccumulateMapper;
import com.hkts.beltweigher.master.service.IDisplaydataService;
import com.hkts.beltweigher.master.service.IRandomNumberSettingsService;
import com.hkts.beltweigher.synchronizationtask.EnviromentConstance;
import com.hkts.beltweigher.utils.*;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.GetMapping;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.hkts.beltweigher.master.service.IYbRunAccumulateService;
import com.hkts.beltweigher.master.entity.YbRunAccumulate;

import javax.servlet.http.HttpServletResponse;

/**
 * @author hml
 * @since 2024-04-10
 */
@RestController
@RequestMapping("/order/ybRunAccumulate")
public class YbRunAccumulateController {
    private final Logger logger = LoggerFactory.getLogger(YbRunAccumulateController.class);

    @Autowired
    public IYbRunAccumulateService iYbRunAccumulateService;
    @Autowired
    private IDisplaydataService iDisplaydataService;
    @Autowired
    private YbClassesAccumulateMapper ybClassesAccumulateMapper;
    @Autowired
    private IRandomNumberSettingsService iRandomNumberSettingsService;

    /**
     * 分页查询数据
     *
     * @param page            分页信息
     * @param ybRunAccumulate 查询条件
     * @return
     */
    @ResponseBody
    @GetMapping("/getYbRunAccumulatePageList")
    public Result<Object> getHontUserList(Page<YbRunAccumulate> page, YbRunAccumulate ybRunAccumulate) {
        return ResultUtil.data(CustomPageUtils.getCustomPage(iYbRunAccumulateService.selectPage(page, ybRunAccumulate)));
    }

    /**
     * 保存和修改公用的
     *
     * @param ybRunAccumulate 传递的实体
     * @return saveOrUpdate
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/ybRunAccumulateSave")
    public Result<Object> ybRunAccumulateSave(YbRunAccumulate ybRunAccumulate) {
        iYbRunAccumulateService.saveOrUpdate(ybRunAccumulate);
        return ResultUtil.success("保存成功");
    }

    /**
     * 根据id获取对象
     *
     * @param id 实体ID
     * @return 0 失败  1 成功
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.GET, value = "/ybRunAccumulateGetById")
    public Result<Object> ybRunAccumulateGetById(String id) {
        YbRunAccumulate byId = iYbRunAccumulateService.getById(id);
        return ResultUtil.data(byId);
    }

    /**
     * 根据id删除对象
     *
     * @param id 实体ID
     * @return 0 失败  1 成功
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/ybRunAccumulateDelete")
    public Result<Object> hontUserDelete(String id) {
        iYbRunAccumulateService.removeById(id);
        return ResultUtil.success("删除成功");
    }

    /**
     * 批量删除对象
     *
     * @param item 实体集合ID
     * @return 0 失败  1 成功
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/ybRunAccumulateBatchDelete")
    public Result<Object> deleteBatchIds(String item) {
        List<String> ids = (List<String>) JSON.parse(item);
        iYbRunAccumulateService.removeByIds(ids);
        return ResultUtil.success("删除成功");
    }

    /**
     *
     * @param startTime
     * @param endTime
     * @return
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.GET, value = "/ybRunAccumulateGetByTime")
    public Result<Object> ybRunAccumulateGetByTime(String startTime, String endTime) throws ParseException {
        return iYbRunAccumulateService.selectList(startTime,endTime);
    }
    @ResponseBody
    @RequestMapping(method = RequestMethod.GET, value = "/ybRunAccumulateGetByClass")
    public Result<Object> ybRunAccumulateGetByClass(Integer type) throws ParseException {
        Displaydata displaydata = new Displaydata();
        List<Displaydata> displaydataList = iDisplaydataService.selectList(displaydata);
        List<YbClassesAccumulate> classesAccumulates = new ArrayList<>();
        Map<String, YbRunAccumulate> ybRunAccumulate = iYbRunAccumulateService.selectYbRunAccumulateByClass(type);
        SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd");
        for (int i = 0; i < displaydataList.size(); i++) {
            if (displaydataList.get(i).getId() < 6) {
                YbClassesAccumulate ybClassesAccumulate = new YbClassesAccumulate();
                ybClassesAccumulate.setDateTime(format.format(DateUtil.getYesterdayDate()));
                ybClassesAccumulate.setInstrumentName(displaydataList.get(i).getInstrumentName());
                ybClassesAccumulate.setClasses(EnviromentConstance.CLASSES_TWO);
                ybClassesAccumulate.setClassesName(EnviromentConstance.CLASSES_NAME_TWO);
                ybClassesAccumulate.setModifyTime(DateUtil.getEightOClock());
                ybClassesAccumulate.setStatisticsDate(DateUtil.getYesterdayDate());
                ybClassesAccumulate.setClassesValue(ybRunAccumulate.get(displaydataList.get(i).getInstrumentName()).getTotal());
                classesAccumulates.add(ybClassesAccumulate);
            }
        }
        if (classesAccumulates.size() > 0) {
            ybClassesAccumulateMapper.batchInsert(classesAccumulates);
        }
        return ResultUtil.data(classesAccumulates);
    }

    /**
     *
     * @param startTime
     * @param endTime
     * @param response
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.GET, value = "/ybRunAccumulateExport")
    public void exportYbRunAccumulate(String startTime, String endTime, HttpServletResponse response) throws IOException, ParseException {
        List<YbRunAccumulate> ybRunAccumulates = iYbRunAccumulateService.selectExportList(startTime, endTime);
        List<Map<String,String>> data = new ArrayList<>();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        for (int i = 0; i < ybRunAccumulates.size(); i++) {
            Map<String,String> ybRunAccumulate = new LinkedHashMap<>();
            ybRunAccumulate.put("仪表",ybRunAccumulates.get(i).getInstrumentName());
            ybRunAccumulate.put("总值",ybRunAccumulates.get(i).getTotal().toString());
            ybRunAccumulate.put("开始值",ybRunAccumulates.get(i).getStartValue().toString());
            ybRunAccumulate.put("结束值",ybRunAccumulates.get(i).getEndValue().toString());
            ybRunAccumulate.put("开始时间",ybRunAccumulates.get(i).getStartTime().format(formatter));
            ybRunAccumulate.put("结束时间",ybRunAccumulates.get(i).getEndTime().format(formatter));
            data.add(ybRunAccumulate);
        }
        XSSFWorkbook wb = new XSSFWorkbook();
        String[] headers = { "仪表", "总值", "开始值", "结束值","开始时间","结束时间"};
        String sheetName = "运行记录";
        String fileName = "运行记录.xlsx";
        ExportExcelUtil.exportExcel(wb,0,sheetName,headers,data);
        response.setContentType("application/octet-stream");
        //设置导出Excel的名称
        response.setHeader("Content-disposition", "attachment;filename=" + new String(fileName.getBytes("gb2312"), "ISO-8859-1"));
        //刷新缓冲
        response.flushBuffer();
        //workbook将Excel写入到response的输出流中，供页面下载该Excel文件
        wb.write(response.getOutputStream());
        //关闭workbook
        wb.close();
    }


    @ResponseBody
    @RequestMapping(method = RequestMethod.GET, value = "/updateRunAccumulate")
    public Result<Object> updateRunAccumulate(){
        List<YbRunAccumulate> ybRunAccumulateList = iYbRunAccumulateService.selectBetweenList(1);
        //排序
        Map<String, List<YbRunAccumulate>> collect = ybRunAccumulateList.stream()
                .collect(Collectors.groupingBy(YbRunAccumulate::getInstrumentName));
        Map<String, List<YbRunAccumulate>> resultMap = new TreeMap<>(collect);
        //获取随机数
        RandomNumberSettings byId = iRandomNumberSettingsService.getById(1);

        Float random = SnowFlakeUtil.getRandom(byId.getStartValue() * byId.getCoefficient(), byId.getEndValue() * byId.getCoefficient());
        //log.info("随机数为:{}", random);
        //计算所有数的总和
        double sum = ybRunAccumulateList.stream()
                .flatMapToDouble(ybRunAccumulate -> DoubleStream.of(ybRunAccumulate.getTotal()))
                .sum();
        //总数大于最大数
        if (sum > byId.getEndValue() * byId.getCoefficient()) {
            Float v = random / (float) sum;
            //求出比率
            for (Map.Entry<String, List<YbRunAccumulate>> entry : resultMap.entrySet()) {

                List<YbRunAccumulate> value = entry.getValue();
                for (int i = 0; i < value.size(); i++) {
                    Float v1 = value.get(i).getTotal() * v;
                    value.get(i).setTotal(v1);
                    value.get(i).setEndValue(value.get(i).getStartValue() + v1);
                    if (i + 1 < value.size() && value.size() > 1) {
                        value.get(i + 1).setStartValue(value.get(i).getStartValue() + v1);
                    }
                }
                iYbRunAccumulateService.saveOrUpdateBatch(value);
            }

        }

        return ResultUtil.data(resultMap);
    }

    @ResponseBody
    @RequestMapping(method = RequestMethod.GET, value = "/updateRunAccumulateAll")
    public Result<Object> updateRunAccumulateAll() {
        iYbRunAccumulateService.selectBetweenListByDate();
        return ResultUtil.success("批量修改历史数据");
    }

    @ResponseBody
    @RequestMapping(method = RequestMethod.GET, value = "/updateRunAccumulateClassAll")
    public Result<Object> updateRunAccumulateClassAll() {
        iYbRunAccumulateService.selectBetweenListClassByDate();
        return ResultUtil.success("批量修改历史数据（班次）");
    }

}
